# -*- coding:UTF-8 -*-
import os
import shutil
import yaml
import zipfile


def upload_file(filename, content, apps_path="AppsTmp", is_save=True):
    if is_save:
        try:
            with open(f"{os.getcwd()}/AppsZip/{filename}", "wb") as f:
                f.write(content)
        except Exception as e:
            return False, f"上传失败: {e}"

    filedir = filename.split(".")[0]
    zip_target_dir = f"{os.getcwd()}/{apps_path}/{filedir}"
    if not os.path.exists(zip_target_dir):
        os.makedirs(zip_target_dir)
    else:
        shutil.rmtree(zip_target_dir)
        os.makedirs(zip_target_dir)
    try:
        with zipfile.ZipFile(f"{os.getcwd()}/AppsZip/{filename}", "r") as zip_ref:
            # 解压所有文件到目标目录
            zip_ref.extractall(zip_target_dir)
    except Exception as e:

        return False, f"上传失败, 解压失败: {e}"

    return True, "上传成功"


def write_docker_file(filename, run_main):
    filedir = filename.split(".")[0]
    app_path = f"{os.getcwd()}/Apps/{filedir}"
    with open("./template/template_docker_base", 'r', encoding="utf-8") as f:
        docker_base = f.read()  # 将文件内容放到一个字符串变量中
        # docker_base = f.readlines() # 一次性读取整个文件；自动将文件内容分析成一个行的列表
    docker_base = docker_base.replace("{code_dir}", app_path)
    docker_base = docker_base.replace("{run_main}", run_main)
    # 读文件内容写入dockerfile
    with open(f"{app_path}/Dockerfile", 'w', encoding='utf-8') as f:
        f.write(docker_base)

    return True


def get_yaml_info(filename, app_path="AppsTmp"):
    filedir = filename.split(".")[0]
    app_path = f"{os.getcwd()}/{app_path}/{filedir}"
    app_yaml_file_path = ""
    yaml_file = {}
    files = os.listdir(app_path)
    _app_path_tmp = f"{os.getcwd()}/Apps/{filedir}"
    for file_tmp in files:
        if file_tmp.find(".yaml") > -1:
            app_yaml_file_path = f"{_app_path_tmp}/{file_tmp}"
            with open(f"{app_path}/{file_tmp}", "r", encoding="utf-8") as f:
                yaml_file = f.read()
            yaml_file = yaml.safe_load(yaml_file)

    if app_yaml_file_path == "":
        if os.path.exists(app_path):
            # 递归地删除文件
            shutil.rmtree(app_path)
        return False, "部署失败, 请检查确保存在yaml文件且格式符合要求", ""

    description = yaml_file.get('info', {}).get(
        'description', "no description")
    if os.path.exists(app_path):
        # 递归地删除文件
        shutil.rmtree(app_path)
    return True, "", description
